//
//  REMViewController.m
//  Raspberry
//
//  Created by 张 锋 on 3/25/14.
//  Copyright (c) 2014 Schneider Electric China. All rights reserved.
//

#import "REMViewController.h"
#import "GCDAsyncSocket.h"
//#import "Communicator.h"


//static Communicator *communicator;

static GCDAsyncSocket *asyncSocket;

@interface REMViewController ()

@property (nonatomic,strong) NSTimer *timer;
@property (nonatomic) float last_value_thr;
@property (nonatomic) float last_value_ele;

@end

@implementation REMViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
    
    self.labelElevator.text = @"0";
    self.labelThrottle.text = @"0";
    
    [self.sliderElevator addTarget:self action:@selector(sliderChanged:) forControlEvents:UIControlEventValueChanged];
    [self.sliderThrottle addTarget:self action:@selector(sliderChanged:) forControlEvents:UIControlEventValueChanged];
    
    [self.switchLed addTarget:self action:@selector(switchChanged:) forControlEvents:UIControlEventValueChanged];
    
    self.last_value_ele = self.sliderElevator.value;
    self.last_value_thr = self.sliderThrottle.value;
}

-(void)tick
{
    if(self.last_value_thr != self.sliderThrottle.value){
        int value = self.sliderThrottle.value * 100;
        
        [self send:[NSString stringWithFormat:@"thr:%3d",value]];
        
        self.last_value_thr = self.sliderThrottle.value;
    }
    
    if(self.last_value_ele != self.sliderElevator.value){
        int value = self.sliderElevator.value * 100;
        
        [self send:[NSString stringWithFormat:@"ele:%3d",value]];
        
        self.last_value_ele = self.sliderElevator.value;
    }
}

-(void)send:(NSString *)message
{
    if(asyncSocket!=nil){
        while(message.length < 7){
            message = [message stringByAppendingString:@"0"];
        }
        
        message = [message stringByAppendingString:@"\0"];
        NSData *data = [message dataUsingEncoding:NSUTF8StringEncoding];
        [asyncSocket writeData:data withTimeout:-1.0 tag:0];
        
        NSLog(@"sending message: %@", message);
    }
    else{
        NSLog(@"socket is null");
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)buttonPressed:(id)sender {
    if(asyncSocket==nil){
        asyncSocket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
        
        NSError *error = nil;
        NSString *ip = self.textIP.text;
        
        if (![asyncSocket connectToHost:ip onPort:2014 error:&error]) {
            NSLog(@"Unable to connect to due to invalid configuration: %@", error);
        }
        else {
            NSLog(@"Connecting...");
        }
        
        [self.button setTitle:@"Disconnect" forState:UIControlStateNormal];
        
        self.timer = [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(tick) userInfo:nil repeats:YES];
    }
    else{
        [self send:@"byebye"];
        [asyncSocket disconnect];
        asyncSocket = nil;
        
        [self.timer invalidate];
        self.timer = nil;
        [self.button setTitle:@"Connect" forState:UIControlStateNormal];
    }
}

- (IBAction)carButtonPressed:(id)sender {
    [self performSegueWithIdentifier:@"toCarView" sender:self];
}

-(void)sliderChanged:(id)sender{
    if([sender isEqual:self.sliderThrottle]){
        int value = self.sliderThrottle.value * 100;
        NSString *valueString = [NSString stringWithFormat:@"%d", value];
        self.labelThrottle.text = valueString;
    }
    if([sender isEqual:self.sliderElevator]){
        int value = self.sliderElevator.value * 100;
        NSString *valueString = [NSString stringWithFormat:@"%d", value];
        self.labelElevator.text = valueString;
    }
}

-(void)switchChanged:(id)sender
{
    NSString *status = self.switchLed.on ? @"001":@"000";
    
    [self send:[NSString stringWithFormat:@"led:%@", status]];
}


- (void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port
{
	NSLog(@"socket:didConnectToHost:%@ port:%hu", host, port);
    
//    NSData *data = [@"0" dataUsingEncoding:NSUTF8StringEncoding];
//	
//	[asyncSocket writeData:data withTimeout:-1.0 tag:0];
}

- (void)socket:(GCDAsyncSocket *)sock didWriteDataWithTag:(long)tag
{
	//NSLog(@"socket:didWriteDataWithTag:");
}

- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
{
	//NSLog(@"socket:didReadData:withTag:");
}

- (void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err
{
	// Since we requested HTTP/1.0, we expect the server to close the connection as soon as it has sent the response.
	
	//NSLog(@"socketDidDisconnect:withError:%@", err);
}
@end
